/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.thread;

import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.client.IUSRequestParams;
import com.apache.client.UctProtoclClient;
import com.apache.database.model.Page;
import com.apache.portal.common.oscache.CacheHelper;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.ConfigUtil;
import com.apache.tools.DataMap;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.ToolsUtil;

import java.util.*;
import java.util.concurrent.Callable;

/**
 * description: 导入任务线程类
 *
 * @author qihan 创建时间：2017-9-14
 */
public class ProExcelImpTask implements Callable<Integer> {

    private List<Map<String, String>> impMap;

    private Map<String, String> reqs;

    private LoginUser loginUser;

    private Map<String,Object> recordMap;

    public ProExcelImpTask(Map<String, String> reqs, List<Map<String, String>> impMap, Map<String,Object> recordMap,
                           LoginUser loginUser) {
        this.impMap = impMap;
        this.reqs = reqs;
        this.recordMap = recordMap;
        this.loginUser = loginUser;
    }

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     *
     * @see Callable#call()
     */
    public Integer call() throws Exception {
        int count = 0;
        List<Map<String, String>> objList = new ArrayList<>();
        List<Map> errProList = new ArrayList<Map>();//记录错误四级分类数据
        List<Map> repeatList = new ArrayList<Map>();//记录数据库重复数据
        try {
            buildParams();
            String beanId = PortalPubFactory.getInstance().getBeanId(reqs.get("datasource"));
            //校验excel分类错误数据
            checkErrList(errProList,impMap);
            //查询出所有产品数据
            ResultEntity entityPro =getProData(beanId);
            //校验重复数据
            objList = checkRepList(impMap,entityPro,repeatList);
            recordMap.put("errProList",errProList);//分类错误数据
            recordMap.put("errProCount",errProList.size());//分类错误数据
            recordMap.put("repeatCount",repeatList.size());//重复数据
            recordMap.put("objCount",objList.size());//正常导入数据
            int result = objList.size();
            if(result>0){
                Map<String, String> params = null;
                String splitAttr = "";
                boolean mark = true;
                int j = 1;

                do {
                    params = new HashMap<String, String>();
                    params.put("sqlKeyId", "sqlKeyId");
                    if (ToolsUtil.isNotNull(reqs.get("rules"))) {
                        params.put("sqlKeyId", reqs.get("rules"));
                        if (Validator.isNotNull(reqs.get("sqlKeyId"))) {
                            params.put(reqs.get("sqlKeyId"), reqs.get("rules"));
                        } else {
                            params.put("beforMethodKey", reqs.get("rules"));
                        }
                    }
                    params.put("resultType", "processSql");
                    params.put("loginUser_userEname", loginUser.getUserEname());//确保其他表中没有该字段
                    params.put("modelTypes", reqs.get("modelTypes"));
                    params.put("sysPass", ConfigUtil.getInstance().interfacePass());
                    params.put("datasource", reqs.get("datasource"));
                    List<Map<String, String>> subList = null;
                    if (100 >= result) {
                        subList = objList;
                        mark = true;
                    } else {
                        int nowNum = j * 200;
                        int startNum = (j - 1) * 200;
                        if (nowNum >= result) {
                            nowNum = result;
                            subList = objList.subList(startNum, nowNum);
                            mark = true;
                        } else {
                            j++;
                            subList = objList.subList(startNum, nowNum);
                        }
                    }
                    for (Map<String, String> imp : subList) {
                        int i = 1;
                        for (String key : imp.keySet()) {
                            String value = StrUtil.doNull(imp.get(key), "-");
                            if (i == 1) {
                                splitAttr = key.replace(reqs.get("objName") + ".", "");
                                params.put(reqs.get("objName") + ".splitAttr", splitAttr);
                            }
                            params.put(key, StrUtil.isNull(params.get(key)) ?
                                    value :
                                    params.get(key) + "-#-" + value);
                            i++;
                        }
                    }
                    Map map = params;
                    map.put(reqs.get("objName")+".createTime",DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                    ResultEntity entity = LoadRpcService.service()
                            .doServiceClient(beanId, "dymicSql", map,
                                    PortalPubFactory.getInstance().getRpcInfo("ius"));
                    if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
                        count += subList.size();
                        if (count == result) {
                            mark = false;
                        }
                    } else {
                        j--;
                    }
                } while (mark);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return count;
    }

    /**
     * 获取产品数据
     * @param beanId
     * @return
     */
    private ResultEntity getProData(String beanId) {
        Map<String, Object> whereParam = new HashMap<String, Object>();
        whereParam.put("modelTypes", "s_caProduction");
        whereParam.put("resultType", "objInfo");
        whereParam.put("resultObjType", "list");
        whereParam.put("sysPass", ConfigUtil.getInstance().interfacePass());
        whereParam.put("result_column", "caProduction.skuName,caProduction.modelSpecification");
        ResultEntity entityPro = LoadRpcService.service().doServiceClient(beanId, "dymicSql", whereParam,
                PortalPubFactory.getInstance().getRpcInfo("ius"));
        return entityPro;
    }

    /**
     * 校验重复数据
     * @param impMap excel数据
     * @param entityPro 数据库数据
     * @param repeatList 记录重复数据
     */
    private List<Map<String, String>>  checkRepList(List<Map<String, String>> impMap, ResultEntity entityPro,List<Map> repeatList) {
        List<DataMap> entityData = (List<DataMap> )entityPro.getEntity();
        List<Map<String, String>> newImpMap = new ArrayList<>();
        List<String> newEntityData = new ArrayList<>();
        for (DataMap dataMap: entityData
             ) {
            String strTmp = dataMap.get("skuName")+"_"+dataMap.get("modelSpecification");
            newEntityData.add(strTmp);
        }
        for (Map<String, String> imp : impMap) {
            String exStr = imp.get("caProduction.skuName")+"_"+imp.get("caProduction.modelSpecification");
            if(newEntityData.contains(exStr)){
                repeatList.add(imp);
            }else{
                newImpMap.add(imp);
            }
        }
        return newImpMap;
    }

    private void buildParams() {
        String pageName = reqs.get("pageName");
        String formName = reqs.get("formName");
        String key = formName + "_" + pageName;
        Map map = (Map) CacheHelper.getInstance().getIusParamCache(key);
        String modelTypes = String.valueOf(map.get("modelTypes"));
        reqs.put("datasource", String.valueOf(map.get("sysName")));
        reqs.put("modelTypes", modelTypes);
        if (modelTypes.startsWith("i_")) {
            reqs.put("objName", modelTypes.substring(2));
        } else if (modelTypes.startsWith("ib_")) {
            reqs.put("objName", modelTypes.substring(3));
        }
        String rules = String.valueOf(map.get("rulesName"));
        reqs.put("rules", rules);
        String evelName = String.valueOf(map.get("evelName"));//方法拦截方式
        reqs.put("sqlKeyId", evelName);
    }
    private void checkErrList(List<Map> errProList,List<Map<String,String>> list){
        List<Map<String,String>> newList =new ArrayList<>();
        List<HashMap> typeList = getProType(reqs);
        boolean flag=true;
        for(int i =0 ;i<list.size();i++){
            Map obj = list.get(i);
            String level4Name = obj.get("caProduction.categoryLevel4").toString();
            loop:for (int k=0 ; k<typeList.size();k++){
                Map category = (HashMap)typeList.get(k).get("eProductCategory");
                String nodeName = category.get("nodeName").toString();
                if(level4Name.equals(nodeName)){
                    flag = false;
                    obj.put("caProduction.categoryLevel4",category.get("nodeNo").toString());
                    obj.put("caProduction.categoryId",category.get("nodeId").toString());
                    String skuId = getSkuId();
                    obj.put("caProduction.skuId",skuId);
                    newList.add(obj);
                    break loop;
                }
            }
            if(flag){
                errProList.add(obj);
            }
        }
        if(errProList.size()>0){
            HashSet hs = new HashSet(errProList);
            errProList.clear();
            errProList.addAll(hs);
        }
        impMap = newList;
    }

    /**
     * 获取所有分类表中第四层级的分类信息
     * @return
     */
    private List getProType(Map<String, String> reqs) {
        List list = new ArrayList();
        try {
            boolean mark = true;
            do {
                Map map = getParams(reqs);
                ResultEntity entity = LoadRpcService.service()
                        .doServiceClient(PortalPubFactory.getInstance().getBeanId("casc"), "dymicSql",
                                map, PortalPubFactory.getInstance().getRpcInfo("ius"));
                if (null == entity.getEntity()) {
                    mark = false;
                } else {
                    if (entity.getEntity() instanceof Page) {
                        Page page = (Page) entity.getEntity();
                        if (!Validator.isEmpty(page.getPageObjects())) {
                            list.addAll(page.getPageObjects());
                            mark = false;
                        } else {
                            mark = false;
                        }
                    } else if(entity.getEntity() instanceof List){
                        list=(List<DataMap>) entity.getEntity();
                        mark = false;
                    }else{
                        mark = false;
                    }
                }
            } while (mark);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return list;
    }

    /**
     * 添加获取分类信息的参数
     * @return
     */
    private Map<String,String> getParams(Map<String, String> reqs) {
        Map<String,String> params = new HashMap();
        params.put("resultType", "objInfo");
        params.put("sysPass", ConfigUtil.getInstance().interfacePass());
        params.put("eProductCategory.w_treeLevel", "4");
        String pageName = reqs.get("categoryPageName");
        String formName = reqs.get("categoryFormName");

        if (StrUtil.isNull(formName) || StrUtil.isNull(pageName)) {
            params.put("sqlKeyId", "sqlKeyId");
            params.put("modelTypes", reqs.get("categoryModelTypes"));
            return null;
        }
        String key = formName + "_" + pageName;

        Map map = (Map) CacheHelper.getInstance()
                .getIusParamCache(key);
        if (ToolsUtil.isEmpty(map)) {
            params.put("sqlKeyId", "sqlKeyId");
            params.put("modelTypes", reqs.get("categoryModelTypes"));
            return null;
        }
        Map resultMap = IUSRequestParams.analyzeParams(map);
        params.putAll(resultMap);
        return params;
    }
    private String getSkuId() {
        String prefix = "HCC";
        String suffix = "BK";
        String userCode = "";
        /**
         *3、调用序号服务端，getSeqNextValue方法参数解释如下：
         *String seqEname：英文序列号标识，int strLen：定义序号编号总长度，不足位自动补齐0
         *int mode：生成模式（0时返回格式如USER0002不带日期，1时返回格式如USER201806110002带日期））
         *         （具体用0/1，请结合实际情况）
         */
        ResultEntity entitySeq = UctProtoclClient.getInstance().getSeqNextValue(prefix,7,0);

        if ("true".equals(entitySeq.getResult()) && !Validator.isEmpty(entitySeq.getEntity())){
            String nextCoed = String.valueOf(entitySeq.getEntity());
            userCode = nextCoed+suffix;	//4、处理返回结果，具体如何替换编号前缀请结合实际情况
        }
        return userCode;
    }
}
